<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-06 13:36:58
 * @LastEditors: whereamazinghappen 306702547@qq.com
 * @LastEditTime: 2023-09-28 10:54:14
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\components\editAddStandardIndex.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 标准指标库的新增或编辑（包括中交和中咨） -->
  <div>
    <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      width="1100px"
      :title="opType == 'add' ? '新增' : opType == 'edit' ? '编辑' : '查看'"
      :before-close="beforeClose"
    >
      <div class="examine-dialog-content">
        <el-form
          :inline="true"
          :model="myForm"
          ref="ruleFormRef"
          :rules="rules"
          label-position="top"
          label-width="120px"
        >
          <el-divider content-position="left">基本信息</el-divider>
          <el-form-item label="父级指标编号" >
            <el-cascader
              style="width: 240px"
              :show-all-levels="false"
              v-model="myForm.parentNumber"
              :options="parentNumOption"
              size="small"
              :disabled="opType == 'look'"
              :props="comData.cascaderprops"
              clearable
            />
          </el-form-item>
<!--          <el-form-item label="子级指标编号" >
            <el-cascader
              style="width: 240px"
              :show-all-levels="false"
              v-model="myForm.parentNumber"
              :options="parentNumOption"
              size="small"
              :disabled="opType == 'look'"
              :props="comData.cascaderprops"
              clearable
            />
          </el-form-item>-->
          <el-form-item label="末位编号" prop="endNumber">
            <el-input
              v-model="myForm.endNumber"
              :disabled="opType == 'look'"
              clearable
              size="small"
              style="width: 240px"
              :maxlength="2"
              :max="99"
              :min="0"
              oninput="value=value.replace(/[^0-9]/g, '')"
            />
          </el-form-item>
          <el-form-item label="指标类型" prop="indexType">
            <el-select
              v-model="myForm.indexType"
              :disabled="opType == 'look'"
              clearable
              style="width: 240px"
              size="small"
            >
              <el-option
                v-for="item in comData.dict_indexTypes"
                :key="item.itemValue"
                :label="item.itemText"
                :value="item.itemValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指标名称" prop="name">
            <!-- 指标类型为类指标时从字典中选择名称 -->
            <el-select
              v-model="myForm.nameCode"
              v-if="myForm.indexType === '1'"
              style="width: 240px"
              @change="nameChange"
              size="small"
              :disabled="opType == 'look'"
              clearable
              :maxlength="30"
              type="text"
            >
              <el-option
                v-for="item in comData.dict_indexNames"
                :key="item.itemValue"
                :label="item.itemText"
                :value="item.itemValue"
              >
              </el-option>
            </el-select>
            <el-input
              v-model="myForm.name"
              :disabled="opType == 'look'"
              v-else
              size="small"
              style="width: 240px"
              maxlength="20" show-word-limit clearable
            /><!-- oninput="value=value.replace(/[^\u4e00-\u9fa5]/g, '')"-->
          </el-form-item>
<!--          <el-form-item label="指标说明(中文填写)" prop="indicatorSpecification">-->
          <el-form-item label="指标说明" prop="indicatorSpecification">
            <el-input
              v-model="myForm.indexIntro"
              autosize
              type="textarea"
              :disabled="opType == 'look'"
              size="small"
              style="width: 990px"
              maxlength="100" show-word-limit clearable


            />
            <!--            <el-input
              v-model="myForm.indexIntro"
              :disabled="opType == 'look'"
              size="small"
              style="width: 990px"
              :maxlength="255"
              autosize
              type="textarea"
            />-->
          </el-form-item>
          <el-divider content-position="left" v-if="isRelated&&myForm.indexType === '3'">关联中交指标</el-divider>
          <div style="width: 100%" v-if="isRelated&&myForm.indexType === '3'">
            <el-form-item label="关联中交年度指标" prop="indexIntro">
              <el-select
                v-model="myForm.superExamineId"
                style="width: 240px"
                @change="annualExamineChange"
                size="small"
                :disabled="opType == 'look'"
                clearable
              >
                <el-option
                  v-for="item in comData.zjAnnualExamines"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联投入产出类指标" prop="indexIntro">
              <el-select
                v-model="myForm.superIndexId"
                style="width: 240px"
                size="small"
                :disabled="opType == 'look'"
                clearable
              >
                <el-option
                  v-for="item in comData.relatedIndexs"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <!-- <span style="float: left">【{{ item.number }}】{{ item.name }}</span> -->
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div v-if="myForm.indexType === '3'">
            <el-divider content-position="left">评分规则</el-divider>
            <el-form-item label="评分类型" prop="scoreType">
              <el-select
                v-model="myForm.scoreType"
                :disabled="opType == 'look'"
                clearable
                style="width: 240px"
                size="small"
              >
                <el-option
                  v-for="item in comData.dict_scoreTypes"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="评分方式" prop="scoreMethod">
              <el-select
                v-model="myForm.scoreMethod"
                :disabled="opType == 'look'"
                clearable
                style="width: 240px"
                size="small"
              >
                <el-option
                  v-for="item in comData.dict_scoreMethods"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="指标分数(H)" prop="score" >
              <el-input
                v-model="myForm.score"
                :disabled="opType == 'look'"
                clearable
                style="width: 240px"
                size="small"
                maxlength="4"  oninput="value=value.replace(/[^\d.-]/g, '').replace(/\.{2,}/g, '.')
                .replace(/-{2,}/g, '-')"

              /><!--                oninput="value=value.replace(/[^\d.]/g, '')
              .replace(/\.{2,}/g, '.').replace('.', '$#$')
              .replace(/\./g, '')
              .replace('$#$', '.')
              .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')@input="handleInput"
              .replace(/^\./g, '')"-->
            </el-form-item>

            <el-form-item
              label="计分组成数据源"
              prop="scoreSource"
              v-if="myForm.scoreMethod === '1'"
            >
              <el-select
                v-model="myForm.scoreSource"
                @change="scoreSoureChange"
                style="width: 240px"
                size="small"
                :disabled="opType == 'look'"
                clearable
              >
                <el-option
                  v-for="item in comData.dict_scoreSources"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-row style="width: 100%">
              <el-form-item label="计分组成" v-if="myForm.scoreMethod === '1'">
                S=
                <span v-for="(item, index) in scoreCompose_arr" :key="'compose' + index"
                  ><el-tag size="large" @close="deleteCompose(index)" closable>{{
                    item.itemText
                  }}</el-tag
                  ><label v-if="index < scoreCompose_arr.length - 1">+</label></span
                >
                <el-select
                  v-model="comData.scoreCompose_sel"
                  @change="composeChange"
                  style="width: 120px; margin-left: 20px"
                  size="small"
                  :disabled="opType == 'look'"
                  placeholder="增加"
                >
                  <el-option
                    v-for="item in comData.dict_composes"
                    :key="item.itemValue"
                    :label="item.itemText"
                    :value="item.itemValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm()" v-if="opType !== 'look'">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ElMessage } from "element-plus";
import { computed, defineComponent, nextTick, reactive, ref, toRefs, watch } from "vue";
import * as api from "../../../api/examineManage";
import pubFc from "../../../utils";
export default defineComponent({
  components: {},
  emits: {
    "update:visible": null,
    refresh: null,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    opType: {
      //操作类型新增或编辑
      type: String,
      default: "add",
    },
    standardType: {
      type: String, //1中交还是2中咨
      default: "1",
    },
    editForm: {
      type: Object, //1中交还是2中咨
    },
    dictDatas: {
      type: Object,
    },
    insertApi: {
      //新增接口，如果有就会在点保存调用该接口
      type: String,
      default: "",
    },
    updateApi: {
      //修改接口
      type: String,
      default: "",
    },
    assignParams: {
      //需要与最终参数混合的参数
      type: Object,
      default: () => {
        return {};
      },
    },
    parentNumOption: {
      //父级编号的options
      type: Array,
      default: () => {
        return [];
      },
    },
    isRelated: {
      //是否需要关联中交
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {


    //表格用到的参数
    // let {standardType,opType}=props;
    const dialogVisible = computed(() => {
      return props.visible;
    });
    const ruleFormRef = ref<any>();
    const rules = reactive<any>({
      //   parentNumber: [{ required: true, message: '请选择父级', trigger: 'blur' }],
      endNumber: [{ required: true, message: "请填写编号", trigger: "blur" }],
      name: [
        { required: true, message: "请填写指标名称(中文名称)", trigger: "blur",  },
        // { pattern: /^[\u4e00-\u9fa5]*$/, message: '只能输入汉字', trigger: 'blur' },
      ],
      indicatorSpecification: [
        { required: false, message: "请填写指标说明(中文名称)", trigger: "blur",  },
        // { pattern: /^[\u4e00-\u9fa5]*$/, message: '只能输入汉字', trigger: 'blur' },
      ],
      indexType: [{ required: true, message: "请选择指标类型", trigger: "blur" }],
      scoreType: [{ required: true, message: "请选择评分规则", trigger: "blur" }],
      scoreMethod: [{ required: true, message: "请选择评分方式", trigger: "blur" }],
      score: [{ required: true, message: "请填写指标分数", trigger: "blur" }],
      scoreSource: [{ required: true, message: "请选择计分组成数据源", trigger: "blur" }],
    });
    let scoreCompose_arr = ref<any>([]);
    const comData = reactive<any>({
      //整体数据带dict全是字典查询
      cascaderprops: {
        checkStrictly: true,
        value: "number",
        label: "number",
        emitPath: false,
      },
      scoreCompose_sel: "",
      // standardAllDatas: [],
      dict_indexTypes: [],
      dict_indexNames: [],
      dict_scoreTypes: [],
      dict_scoreMethods: [],
      dict_scoreSources: [],
      dict_composes: [],
      dict_all_scoreCompose: [],
      zjAnnualExamines: [],
      relatedIndexs: [],
    });
    const backData = {
      endNumber: "",
      indexType: "",
      parentNumber: "",
      name: "",
      nameCode: "",
      indexIntro: "",
      scoreType: "",
      scoreMethod: "",
      score: "",
      scoreSource: "",
      scoreCompose: [],
      superExamineId: "",
      superIndexId: "",
    };
    const handleInput = () => {
/*      myForm.score = myForm.score.replace(/[^\d.]/g, "")
          .replace(/(\..*)\./g, "$1") // 去除多余的小数点
          // .replace(/^-/g, "") // 去除开头的负号
          .replace(/^\./g, "") // 去除开头的小数点
          .replace(/(\d*\.\d{2}).*$/, "$1"); // 限制小数位数为两位
      if (myForm.score > 99) {
      myForm.score = 99;
      } else if (myForm.score < -99) {
          myForm.score = -99;
      }*/
      // var inputValue = document.getElementById("inputId").value;
      // inputValue = inputValue.replace(/-{2,}/g, '-');
      // document.getElementById("inputId").value = inputValue;
    };
    const myForm = reactive<any>({ ...backData });
    watch(
      () => props.visible,
      (newval) => {
        if (newval) {
          scoreCompose_arr.value = [];
          // getStandardList()
          nextTick(() => {
            //初始绑定需在form完成初始化\
            ruleFormRef.value?.resetFields();
            resetFormMyself(); //当form表单一开始是v-if隐藏时就不能清空，需额外单独清空

            if (
              props.opType == "edit" ||
              props.opType == "copy" ||
              props.opType == "look"
            ) {
              // console.log('props.editForm',props.editForm);
              pubFc.ojectCopyObj(myForm, props.editForm);
              if (myForm.scoreCompose) {
                scoreCompose_arr.value = myForm.scoreCompose.map((item) => {
                  let c = comData.dict_all_scoreCompose.find(
                    (com) => com.itemValue === item
                  );
                  return c;
                });
              }
              if (myForm.scoreSource) {
                findComposeDict(myForm.scoreSource);
              }
              if (props.isRelated) {
                annualExamineChange(myForm.superExamineId, false);
              }
            }
          });
        }
      }
    );
    const annualExamineChange = (value, resetId = true) => {
      if (resetId) myForm.superIndexId = "";
      if (!value) {
        comData.relatedIndexs = [];
      } else {
        api
          .getListByAnnualIdRequest({
            annualId: value,
          })
          .then((res) => {
            res.data.data.map((item) => {
              item.name = `【${item.number}】${item.name}`;
            });
            comData.relatedIndexs = res.data.data;
          });
      }
    };
    const beforeClose = () => {
      cancel();
    };
    const cancel = () => {
      emit("update:visible", false);
    };
    const confirm = () => {
      //确定新增或修改
      console.log(myForm);
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          dealParams();
          let apiName = "",
            params = {
              ...myForm,
              ...props.assignParams,
              id: "",
            };
          if (props.opType === "add" || props.opType === "copy") {
            apiName = props.insertApi;
            delete params.id;
          } else {
            apiName = props.updateApi;
            params.id = props.editForm?.id;
          }

          api[apiName](params).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: props.opType === "edit" ? "成功修改" : "成功创建",
                type: "success",
              });
              cancel();
              emit("refresh");
            }
          });
        }
      });
    };
    const resetFormMyself = () => {
      //单独清空字段
      myForm.scoreType = "";
      myForm.parentNumber = "";
      myForm.indexIntro = "";
      myForm.scoreMethod = "";
      myForm.score = "";
      myForm.scoreSource = "";
      comData.dict_composes = [];
      myForm.superExamineId = "";
      myForm.superIndexId = "";
      comData.relatedIndexs = [];
    };
    const dealParams = () => {
      //处理新增或编辑前的参数
      if (myForm.indexType !== "3") {
        //如果不是评分指标就清空评分规则中的所有字段
        myForm.scoreType = "";
        myForm.scoreMethod = "";
        myForm.score = "";
        myForm.scoreSource = "";
      }
      if (myForm.scoreMethod === "1") {
        myForm.scoreCompose = scoreCompose_arr.value.map((item) => {
          return item.itemValue;
        });
      } else {
        myForm.scoreCompose = [];
      }
      if (myForm.indexType !== "1") {
        myForm.nameCode = "";
      }
    };
    const scoreSoureChange = (value) => {
      //根据数据源查询对应的计分组成字典
      let current = comData.dict_scoreSources.filter((item) => item.itemValue === value);
      if (current) {
        comData.dict_composes = current[0].children;
        scoreCompose_arr.value = [];
      } else {
        comData.dict_composes = [];
      }
    };
    const findComposeDict = (value) => {
      comData.dict_composes = [];
      let current = comData.dict_scoreSources.filter((item) => item.itemValue === value);
      if (current) {
        comData.dict_composes = current[0].children;
      }
    };
    const composeChange = (value) => {
      let current = comData.dict_composes.filter((item) => item.itemValue === value);
      scoreCompose_arr.value.push(toRefs(current[0]));
      comData.scoreCompose_sel = "";
    };
    const nameChange = (value) => {
      let current = comData.dict_indexNames.filter((item) => item.itemValue === value);
      myForm.name = current[0].itemText;
    };
    const deleteCompose = (index: number) => {
      scoreCompose_arr.value.splice(index, 1);
    };

    watch(
      () => props.dictDatas,
      (newval) => {
        getDictDatas(newval);
      },
      { deep: true }
    );
    // const getStandardList = () => {
    //   api
    //     .superIndexSdBanklistRequest({
    //       type: props.standardType, //1-中交标准指标、2-中咨标准指标
    //     })
    //     .then((res) => {
    //       comData.standardAllDatas = res.data.data
    //     })
    // }
    const getDictDatas = (dictDatas) => {
      comData.dict_indexTypes = dictDatas.dict_indexTypes;
      comData.dict_indexNames = dictDatas.dict_indexNames;
      comData.dict_scoreTypes = dictDatas.dict_scoreTypes;
      comData.dict_scoreMethods = dictDatas.dict_scoreMethods;
      if (props.standardType === "1") {
        //中交
        comData.dict_scoreSources = dictDatas.dict_scoreSources_zj;
        comData.dict_all_scoreCompose = dictDatas.dict_scoreCompose_zj;
      } else {
        //中咨
        comData.dict_scoreSources = dictDatas.dict_scoreSources_zz;
        comData.dict_all_scoreCompose = dictDatas.dict_scoreCompose_zz;
      }
    };
    const getZjAnnualList = () => {
      //查询可关联的中交年度考核

      api
        .getZjAnnuallsitRequest({
          current: 1,
          size: 1011,
        })
        .then((res) => {
          comData.zjAnnualExamines = res.data.data.records;
        });
    };

    if (props.isRelated) {
      getZjAnnualList();
    }
    return {
      scoreCompose_arr,
      comData,
      myForm,
      dialogVisible,
      rules,
      ruleFormRef,
      cancel,
      confirm,
      scoreSoureChange,
      composeChange,
      nameChange,
      deleteCompose,
      beforeClose,
      annualExamineChange,
      handleInput,
    };
  },
});
</script>
<style lang="scss" scoped>
.examine-dialog-content {
  padding: 20px;
  max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    -ms-overflow-style: none;
}


</style>
